<template>
  <div class="pieEcharts">
    <div :id="elId"></div>
  </div>
</template>
<script>
  let echarts = require('echarts/lib/echarts')
  // 引入饼状图组件
  require('echarts/lib/chart/pie')
  // 引入提示框和title组件
  require('echarts/lib/component/tooltip')
  require('echarts/lib/component/title')
  //引入uuid文件
  import uuidv1 from 'uuid/v1'
  export default {
    name: 'ageEchartss',
    props: {        //接受父组件传递来的数据
      items : {
        type: Array,
        default() {    //默认数据，没有数剧的情况下启用
          return [{ name: '男', value: 8 }, { name: '女', value: 7 }]
        }
      },
      name : {
        type: String ,
        default: '性别'  //默认数据，没有数剧的情况下启用
      }
    },
    data() {
      return {
        elId: ''
      }
    },
    watch: {
      items: {
        handler(curVal, oldVal) { //监听登陆人的科室有没改变，如果改变就执行下面的方法
          //console.log(curVal)  //新值
          this.drawAge();
        }
      }
    
    },
    created() {
      this.elId = uuidv1() //获取随机id
    },
    mounted() {
      this.drawAge();
    },
    methods: {
      drawAge() {
        let values = [] //提炼接收到的数据
        this.items.forEach(el => {
          values.push(el.value)
        })
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}: {c} ({d}%)"
          },
          series: [{
            name: this.name,
            type: 'pie',
            radius: ['60%', '80%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'inner', //标签的位置
                textStyle: {
                  fontSize: '12',
                  fontWeight: 'normal'
                },
                formatter: '{b}: {c}'
              },
            },
            labelLine: {
              normal: {
                show: true
              }
            },
            data: this.items
          }],
          color: ['#F44336', '#11A7F3', '#FFBA06', '#02BB96']
        }
        //初始化
        const chartObj = echarts.init(document.getElementById(this.elId))
        chartObj.setOption(option)
        window.addEventListener('resize', function () {
          chartObj.resize()
        })
      }
    }

  }
</script>
<style scoped>
  .pieEcharts > div {
    width: 80%;
    height: 100px;
    box-sizing: border-box;
  }
</style>
